// 游戏状态枚举
const GameState = {
    SELECTING_ATTRIBUTE: 'selecting_attribute', // 选择属性阶段
    DRAWING: 'drawing', // 抽卡阶段
    PLACING: 'placing', // 放置卡牌阶段
    BATTLE: 'battle' // 战斗阶段
};

// 卡牌属性枚举
const Attributes = {
    GOLD: '金',
    WOOD: '木',
    WATER: '水',
    FIRE: '火',
    EARTH: '土'
};

// 名字和描述库
const NAMES = [
    // 诗人
    '李白', '杜甫', '苏轼', '王维', '白居易', '陆游', '辛弃疾', 
    // 画家
    '张择端', '顾恺之', '吴道子', '范宽', '郭熙', 
    // 科学家
    '祖冲之', '张衡', '沈括', '李时珍', '华罗庚', '杨振宁', 
    // 军事家
    '孙武', '诸葛亮', '岳飞'
];

const DESCRIPTIONS = {
    monster: {
        '金': [
            '金戈铁马，气吞万里',
            '金光闪耀，威震四方',
            '金刚不坏，固若金汤'
        ],
        '木': [
            '根深叶茂，生机勃勃',
            '青松挺立，傲雪凌霜',
            '木秀于林，风必摧之'
        ],
        '水': [
            '上善若水，厚德载物',
            '水到渠成，势如破竹',
            '江河汇聚，气势磅礴'
        ],
        '火': [
            '烈火燎原，势不可挡',
            '星火燎原，光耀四方',
            '火光冲天，威震八方'
        ],
        '土': [
            '厚德载物，稳如泰山',
            '土木相生，固若金汤',
            '大地之力，坚不可摧'
        ]
    },
    magic: [
        '运筹帷幄，决胜千里',
        '妙手回春，化腐朽为神奇',
        '天地玄黄，宇宙洪荒',
        '移山倒海，改天换地'
    ]
};

// 为卡牌生成唯一ID
let cardIdCounter = 0;
function generateCardId() {
    return `card_${cardIdCounter++}`;
}

class Card {
    constructor(name, type, attribute) {
        this.id = generateCardId();
        this.name = name;
        this.type = type;
        this.attribute = attribute;
        this.description = this.generateDescription();
        this.canAttack = true;
        
        if (type === 'monster') {
            this.stats = this.generateMonsterStats(attribute);
            this.position = 'attack';
        } else {
            this.effect = this.generateMagicEffect();
        }
    }

    generateDescription() {
        if (this.type === 'monster') {
            const descriptions = DESCRIPTIONS.monster[this.attribute];
            return `${this.name}：${descriptions[Math.floor(Math.random() * descriptions.length)]}`;
        } else {
            return `${this.name}：${DESCRIPTIONS.magic[Math.floor(Math.random() * DESCRIPTIONS.magic.length)]}`;
        }
    }

    generateMonsterStats(attribute) {
        let attack, defense, health;
        const rand = Math.random();
        
        switch(attribute) {
            case Attributes.GOLD: // 金属性：80%的怪兽攻击力大于守备力，守备力大于血量
                if (rand < 0.8) {
                    attack = Math.floor(Math.random() * 4) + 4; // 4-7
                    defense = Math.floor(Math.random() * 3) + 2; // 2-4
                    health = Math.floor(Math.random() * 2) + 1; // 1-2
                } else {
                    attack = Math.floor(Math.random() * 7) + 1;
                    defense = Math.floor(Math.random() * 7) + 1;
                    health = Math.floor(Math.random() * 5) + 1;
                }
                break;
                
            case Attributes.WOOD: // 木属性：80%的怪兽血量大于守备力，守备力大于攻击力
                if (rand < 0.8) {
                    health = Math.floor(Math.random() * 3) + 3; // 3-5
                    defense = Math.floor(Math.random() * 2) + 2; // 2-3
                    attack = Math.floor(Math.random() * 2) + 1; // 1-2
                } else {
                    attack = Math.floor(Math.random() * 7) + 1;
                    defense = Math.floor(Math.random() * 7) + 1;
                    health = Math.floor(Math.random() * 5) + 1;
                }
                break;
                
            case Attributes.WATER: // 水属性：80%的怪兽守备力大于攻击力，攻击力大于血量
                if (rand < 0.8) {
                    defense = Math.floor(Math.random() * 3) + 4; // 4-6
                    attack = Math.floor(Math.random() * 3) + 2; // 2-4
                    health = Math.floor(Math.random() * 2) + 1; // 1-2
                } else {
                    attack = Math.floor(Math.random() * 7) + 1;
                    defense = Math.floor(Math.random() * 7) + 1;
                    health = Math.floor(Math.random() * 5) + 1;
                }
                break;
                
            case Attributes.FIRE: // 火属性：80%的怪兽攻击力大于血量，血量大于守备力
                if (rand < 0.8) {
                    attack = Math.floor(Math.random() * 3) + 5; // 5-7
                    health = Math.floor(Math.random() * 2) + 2; // 2-3
                    defense = Math.floor(Math.random() * 2) + 1; // 1-2
                } else {
                    attack = Math.floor(Math.random() * 7) + 1;
                    defense = Math.floor(Math.random() * 7) + 1;
                    health = Math.floor(Math.random() * 5) + 1;
                }
                break;
                
            case Attributes.EARTH: // 土属性：80%的怪兽守备力大于血量，血量大于攻击力
                if (rand < 0.8) {
                    defense = Math.floor(Math.random() * 3) + 4; // 4-6
                    health = Math.floor(Math.random() * 2) + 2; // 2-3
                    attack = Math.floor(Math.random() * 2) + 1; // 1-2
                } else {
                    attack = Math.floor(Math.random() * 7) + 1;
                    defense = Math.floor(Math.random() * 7) + 1;
                    health = Math.floor(Math.random() * 5) + 1;
                }
                break;
        }
        
        return { attack, defense, health };
    }

    generateMagicEffect() {
        const effects = [
            { type: 'attack', value: Math.floor(Math.random() * 3) + 1 },
            { type: 'defense', value: Math.floor(Math.random() * 3) + 1 },
            { type: 'health', value: Math.floor(Math.random() * 3) + 1 }
        ];
        return effects[Math.floor(Math.random() * effects.length)];
    }
}

class Player {
    constructor(isBot = false) {
        this.isBot = isBot;
        this.lifePoints = 15;
        this.deck = [];
        this.hand = [];
        this.monsterZone = [];
        this.magicZone = [];
        this.graveyard = [];
        this.attribute = null;

    }

    initializeDeck(attribute) {
        this.attribute = attribute;
        this.deck = [];

        
        for (let i = 0; i < 40; i++) {
            const isMonster = i < 32;
            let name;
            name = NAMES[Math.floor(Math.random() * NAMES.length)];
            
       
            const card = new Card(name, isMonster ? 'monster' : 'magic', attribute);
            this.deck.push(card);
        }
        
        this.shuffleDeck();
    }

    shuffleDeck() {
        for (let i = this.deck.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this.deck[i], this.deck[j]] = [this.deck[j], this.deck[i]];
        }
    }

    canDrawCard() {
        return this.deck.length > 0 && this.hand.length < 6;
    }

    drawCard() {
        if (!this.canDrawCard()) {
            if (this.deck.length === 0) {
                return { success: false, message: '卡组已空' };
            }
            if (this.hand.length >= 8) {
                return { success: false, message: '手牌已满' };
            }
        }

        const card = this.deck.pop();
        this.hand.push(card);
        return { success: true, card };
    }

    discardCard(card) {
        const index = this.hand.indexOf(card);
        if (index > -1) {
            this.hand.splice(index, 1);
            this.graveyard.push(card);
            return true;
        }
        return false;
    }

    getAttackableMonsters() {
        return this.monsterZone.filter(monster => 
            monster.position === 'attack' && monster.canAttack);
    }

    resetMonstersAttackState() {
        this.monsterZone.forEach(monster => {
            monster.canAttack = true;
        });
    }
}

class GameModel {
    constructor() {
        this.player = null;
        this.robot = null;
        this.currentState = null;
        this.currentPlayer = null;
    }

    initialize() {
        this.player = new Player(false);
        this.robot = new Player(true);
        this.currentState = GameState.SELECTING_ATTRIBUTE;
        this.currentPlayer = null;
    }

    // 游戏逻辑方法
    initializePlayerDeck(attribute) {
        this.player.initializeDeck(attribute);
        for (let i = 0; i < 6; i++) {
            this.player.drawCard();
        }
    }

    initializeRobotDeck() {
        this.robot.initializeDeck(Attributes.EARTH);
        for (let i = 0; i < 6; i++) {
            this.robot.drawCard();
        }
    }

    // 状态检查方法
    canPlaceCard(card, zone) {
        if (zone === 'monster') {
            return this.currentPlayer.monsterZone.length < 5;
        } else if (zone === 'magic') {
            return this.currentPlayer.magicZone.length < 3;
        }
        return false;
    }

    canAttack(monster) {
        return monster.position === 'attack' && 
               monster.canAttack && 
               this.currentState === GameState.BATTLE;
    }

    canActivateMagic(magicCard) {
        return this.currentState === GameState.BATTLE &&
               this.currentPlayer.magicZone.includes(magicCard);
    }

    // 卡牌操作方法
    placeCard(card, zone, position = 'attack') {
        if (!this.canPlaceCard(card, zone)) {
            return false;
        }

        if (zone === 'monster') {
            card.position = position;
            this.currentPlayer.monsterZone.push(card);
        } else {
            this.currentPlayer.magicZone.push(card);
        }
        
        const index = this.currentPlayer.hand.indexOf(card);
        if (index > -1) {
            this.currentPlayer.hand.splice(index, 1);
        }
        
        return true;
    }

    // 战斗相关方法
    calculateBattleDamage(attacker, defender) {
        if (defender.position === 'defense') {
            return attacker.stats.attack > defender.stats.defense ? 
                attacker.stats.attack - defender.stats.defense : 0;
        }
        return attacker.stats.attack;
    }

    battle(attacker, defender) {
        if (!this.canBattle() || !attacker.canAttack) {
            return { success: false, message: '无法进行攻击' };
        }

        let damage = 0;
        let message = '';
        const attributeBonus = this.getAttributeBonus(attacker, defender);
        let attributeMessage = this.getAttributeMessage(attacker, defender, attributeBonus);

        if (defender.position === 'attack') {
            const attackerPower = Math.floor(attacker.stats.attack * attributeBonus);
            const defenderPower = defender.stats.attack;

            if (attackerPower > defenderPower) {
                damage = attackerPower - defenderPower;
                defender.stats.health -= damage;
                this.getOpponent().lifePoints -= damage;
                message = `${attacker.name} 击败了 ${defender.name}，造成 ${damage} 点伤害！`;
                
                // 立即检查生命值
                if (this.getOpponent().lifePoints <= 0) {
                    const winner = this.currentPlayer === this.player ? '玩家' : '机器人';
                    message += `\n${winner}获得胜利！`;
                    return {
                        success: true,
                        message,
                        damage,
                        gameOver: true,
                        winner
                    };
                }
            } else if (attackerPower < defenderPower) {
                damage = defenderPower - attackerPower;
                attacker.stats.health -= damage;
                this.currentPlayer.lifePoints -= damage;
                message = `${attacker.name} 被 ${defender.name} 击败，受到 ${damage} 点伤害！`;
                
                // 立即检查生命值
                if (this.currentPlayer.lifePoints <= 0) {
                    const winner = this.currentPlayer === this.player ? '机器人' : '玩家';
                    message += `\n${winner}获得胜利！`;
                    return {
                        success: true,
                        message,
                        damage,
                        gameOver: true,
                        winner
                    };
                }
            } else {
                message = '双方势均力敌，不分胜负！';
            }
        } else {
            // 攻击防御表示怪兽
            const attackerPower = Math.floor(attacker.stats.attack * attributeBonus);
            const defenderPower = defender.stats.defense;

            if (attackerPower > defenderPower) {
                // 攻击方突破防御
                damage = attackerPower - defenderPower;
                defender.stats.health -= damage;
                message = `${attacker.name} 突破了 ${defender.name} 的防御，造成 ${damage} 点伤害！`;
            } else {
                message = `${defender.name} 成功防御了攻击！`;
            }
        }

        // 添加属性相克信息
        if (attributeMessage) {
            message = attributeMessage + '\n' + message;
        }

        // 标记怪兽已攻击
        attacker.canAttack = false;

        // 检查怪兽是否被摧毁
        const destroyedMonsters = this.checkMonsterDestruction();
        if (destroyedMonsters.player || destroyedMonsters.robot) {
            message += this.getDestructionMessage(destroyedMonsters);
        }

        // 在造成伤害后立即检查游戏结束
        const gameEndResult = this.checkGameEnd();
        if (gameEndResult.gameOver) {
            message += `\n${gameEndResult.winner}获得胜利！`;
        }

        return { 
            success: true, 
            message, 
            damage,
            gameOver: gameEndResult.gameOver,
            winner: gameEndResult.winner 
        };
    }

    getAttributeMessage(attacker, defender, bonus) {
        if (bonus === 1) return '';
        
        const relationships = {
            '金': { '木': '金克木', '火': '金畏火' },
            '木': { '土': '木克土', '金': '木畏金' },
            '水': { '火': '水克火', '土': '水畏土' },
            '火': { '金': '火克金', '水': '火畏水' },
            '土': { '水': '土克水', '木': '土畏木' }
        };

        const relation = relationships[attacker.attribute]?.[defender.attribute];
        if (!relation) return '';

        if (bonus > 1) {
            return `${relation}，${attacker.name}的攻击力提升了！`;
        } else {
            return `${relation}，${attacker.name}的攻击力减弱了！`;
        }
    }

    directAttack(monster) {
        if (!this.canDirectAttack()) {
            return { success: false, message: '无法进行直接攻击' };
        }

        const damage = monster.stats.attack;
        this.getOpponent().lifePoints -= damage;
        monster.canAttack = false;

        let message = `${monster.name}发动直接攻击！\n` +
                     `${this.getOpponent() === this.player ? '玩家' : '机器人'}受到 ${damage} 点伤害！`;

        // 立即检查生命值
        if (this.getOpponent().lifePoints <= 0) {
            const winner = this.currentPlayer === this.player ? '玩家' : '机器人';
            message += `\n${winner}获得胜利！`;
            return {
                success: true,
                message,
                damage,
                gameOver: true,
                winner
            };
        }

        return {
            success: true,
            message,
            damage,
            gameOver: false
        };
    }

    activateMagicCard(magicCard, target) {
        if (!this.canUseMagic()) {
            return { success: false, message: '无法使用魔法卡' };
        }

        const effect = magicCard.effect;
        let message = '';

        switch (effect.type) {
            case 'attack':
                target.stats.attack += effect.value;
                message = `${magicCard.name} 增加了 ${target.name} 的攻击力 ${effect.value} 点！`;
                break;
            case 'defense':
                target.stats.defense += effect.value;
                message = `${magicCard.name} 增加了 ${target.name} 的防御力 ${effect.value} 点！`;
                break;
            case 'health':
                target.stats.health += effect.value;
                message = `${magicCard.name} 增加了 ${target.name} 的生命值 ${effect.value} 点！`;
                break;
        }

        // 将魔法卡移到墓地
        const index = this.currentPlayer.magicZone.indexOf(magicCard);
        if (index > -1) {
            this.currentPlayer.magicZone.splice(index, 1);
            this.currentPlayer.graveyard.push(magicCard);
        }

        return { success: true, message };
    }

    // AI逻辑
    async executeBotTurn() {
        // 放置阶段的策略改进
        this.botPlaceCards();

        // 战斗阶段的策略改进
        this.currentState = GameState.BATTLE;
        await this.botExecuteBattle();

        // 使用魔法卡的策略改进
        this.botUseMagicCards();
    }

    botPlaceCards() {
        const availableMonsterSlots = this.getAvailableMonsterZoneSlots(this.robot);
        const availableMagicSlots = this.getAvailableMagicZoneSlots(this.robot);

        // 优化怪兽放置策略
        if (availableMonsterSlots > 0) {
            const monsters = this.robot.hand
                .filter(card => card.type === 'monster')
                .sort((a, b) => {
                    // 计算每个怪兽的综合评分
                    const scoreA = this.evaluateMonsterValue(a);
                    const scoreB = this.evaluateMonsterValue(b);
                    return scoreB - scoreA;
                })
                .slice(0, availableMonsterSlots);

            monsters.forEach(monster => {
                const position = this.determineBestPosition(monster);
                this.placeCard(monster, 'monster', position);
            });
        }

        // 优化魔法卡放置策略
        if (availableMagicSlots > 0) {
            const magics = this.robot.hand
                .filter(card => card.type === 'magic')
                .sort((a, b) => {
                    const scoreA = this.evaluateMagicCardValue(a);
                    const scoreB = this.evaluateMagicCardValue(b);
                    return scoreB - scoreA;
                })
                .slice(0, availableMagicSlots);

            magics.forEach(magic => {
                this.placeCard(magic, 'magic');
            });
        }
    }

    // 评估怪兽的综合价值
    evaluateMonsterValue(monster) {
        let score = 0;
        
        // 基础属性评分
        score += monster.stats.attack * 1.5;  // 攻击力权重更高
        score += monster.stats.defense;
        score += monster.stats.health * 2;    // 生命值权重更高

        // 属性相克加分
        const playerMonsters = this.player.monsterZone;
        if (playerMonsters.length > 0) {
            const attributeBonus = Math.max(
                ...playerMonsters.map(pm => this.getAttributeBonus(monster, pm))
            );
            score += (attributeBonus > 1 ? 3 : 0);  // 有克制关系加分
        }

        // 场上形势评分
        if (this.player.monsterZone.length === 0) {
            score += monster.stats.attack * 0.5;  // 对手场空，攻击力更重要
        }

        // 生命值差距评分
        const lifeDiff = this.robot.lifePoints - this.player.lifePoints;
        if (lifeDiff < 0) {
            score += monster.stats.defense * 0.5;  // 落后时防御更重要
        }

        return score;
    }

    // 评估魔法卡的价值
    evaluateMagicCardValue(magic) {
        let score = 0;
        const robotMonsters = this.robot.monsterZone;
        const playerMonsters = this.player.monsterZone;

        // 根据场上形势评估魔法卡效果
        switch (magic.effect.type) {
            case 'attack':
                // 当我方有强攻击力怪兽或对手场空时，攻击力提升更有价值
                if (robotMonsters.some(m => m.stats.attack >= 4) || playerMonsters.length === 0) {
                    score += magic.effect.value * 2;
                }
                break;
            case 'defense':
                // 当我方生命值较低或对手有强攻击力怪兽时，防御力提升更有价值
                if (this.robot.lifePoints < 10 || playerMonsters.some(m => m.stats.attack >= 4)) {
                    score += magic.effect.value * 2;
                }
                break;
            case 'health':
                // 当我方有重要怪兽且生命值较低时，生命值提升更有价值
                if (robotMonsters.some(m => m.stats.health <= 2 && (m.stats.attack >= 4 || m.stats.defense >= 4))) {
                    score += magic.effect.value * 3;
                }
                break;
        }

        return score;
    }

    // 决定怪兽的最佳放置位置
    determineBestPosition(monster) {
        // 根据场上形势和怪兽属性决定攻守
        const playerMonsters = this.player.monsterZone;
        
        // 如果对手场上没有怪兽，优先攻击表示
        if (playerMonsters.length === 0) {
            return 'attack';
        }

        // 计算对手最强攻击力
        const maxEnemyAttack = Math.max(...playerMonsters.map(m => m.stats.attack), 0);

        // 如果我方生命值较低，倾向于防守
        if (this.robot.lifePoints < 8) {
            return monster.stats.defense > monster.stats.attack ? 'defense' : 'attack';
        }

        // 根据属性相克和攻防对比决定
        const hasAdvantage = playerMonsters.some(pm => this.getAttributeBonus(monster, pm) > 1);
        if (hasAdvantage && monster.stats.attack >= maxEnemyAttack * 0.8) {
            return 'attack';  // 有属性优势且攻击力接近时选择攻击
        }

        // 默认根据攻防值对比决定
        return monster.stats.defense > monster.stats.attack + 1 ? 'defense' : 'attack';
    }

    // 优化战斗决策
    async botExecuteBattle() {
        const attackers = this.robot.monsterZone.filter(m => m.position === 'attack' && m.canAttack);
        if (attackers.length === 0) return;

        const playerMonsters = this.player.monsterZone;
        
        // 如果对手场空，直接攻击
        if (playerMonsters.length === 0) {
            attackers.forEach(attacker => {
                this.directAttack(attacker);
            });
            return;
        }

        // 为每个攻击者选择最佳目标
        attackers.forEach(attacker => {
            const bestTarget = this.findBestAttackTarget(attacker, playerMonsters);
            if (bestTarget) {
                this.battle(attacker, bestTarget);
            }
        });
    }

    // 找到最佳攻击目标
    findBestAttackTarget(attacker, targets) {
        let bestTarget = null;
        let bestValue = -Infinity;

        targets.forEach(target => {
            const value = this.evaluateAttackValue(attacker, target);
            if (value > bestValue) {
                bestValue = value;
                bestTarget = target;
            }
        });

        // 只在有利时发动攻击
        return bestValue > 0 ? bestTarget : null;
    }

    // 评估攻击价值
    evaluateAttackValue(attacker, defender) {
        const attributeBonus = this.getAttributeBonus(attacker, defender);
        const effectiveAttack = Math.floor(attacker.stats.attack * attributeBonus);

        let value = 0;

        if (defender.position === 'attack') {
            // 攻击表示怪兽
            const damageDiff = effectiveAttack - defender.stats.attack;
            value = damageDiff;  // 基础分数为伤害差值

            // 考虑属性相克
            if (attributeBonus > 1) value += 2;
            
            // 考虑目标怪兽的威胁度
            value += defender.stats.attack * 0.5;
            
            // 如果可以击破且不会受到太多反伤，加分
            if (damageDiff > 0 && damageDiff > -attacker.stats.health) {
                value += 3;
            }
        } else {
            // 防御表示怪兽
            const damageDiff = effectiveAttack - defender.stats.defense;
            value = damageDiff * 0.7;  // 攻击防御表示怪兽的价值略低

            // 如果可以击破且目标生命值较低，加分
            if (damageDiff > 0 && defender.stats.health <= 2) {
                value += 2;
            }
        }

        return value;
    }

    botUseMagicCards() {
        const magicCards = [...this.robot.magicZone];
        const allMonsters = [
            ...this.robot.monsterZone,
            ...this.player.monsterZone
        ].filter(monster => monster.position === 'attack');

        magicCards.forEach(magic => {
            const { target, value } = this.getBestMagicTarget(magic, true);
            if (target && value > 0) {
                this.activateMagicCard(magic, target);
            }
        });
    }

    checkGameEnd() {
        if (this.player.lifePoints <= 0) {
            return { gameOver: true, winner: '机器人' };
        } else if (this.robot.lifePoints <= 0) {
            return { gameOver: true, winner: '玩家' };
        }
        return { gameOver: false };
    }

    switchTurn() {
        this.currentPlayer = this.currentPlayer === this.player ? this.robot : this.player;
        this.currentPlayer.resetMonstersAttackState();
        this.currentState = GameState.DRAWING;
    }

    // 添加新的辅助方法
    getMonstersByPosition(player, position) {
        return player.monsterZone.filter(monster => monster.position === position);
    }

    getAvailableMonsterZoneSlots(player) {
        return 5 - player.monsterZone.length;
    }

    getAvailableMagicZoneSlots(player) {
        return 3 - player.magicZone.length;
    }

    // 检查是否有可用的魔法卡目标
    hasValidMagicTargets() {
        return this.player.monsterZone.some(monster => monster.position === 'attack') ||
               this.robot.monsterZone.some(monster => monster.position === 'attack');
    }

    // 检查是否可以进行战斗
    canBattle() {
        return this.currentState === GameState.BATTLE &&
               this.currentPlayer.monsterZone.some(monster => 
                   monster.position === 'attack' && monster.canAttack);
    }

    // 检查是否可以直接攻击
    canDirectAttack() {
        const opponent = this.currentPlayer === this.player ? this.robot : this.player;
        return this.canBattle() && opponent.monsterZone.length === 0;
    }

    // 获取最佳魔法卡目标
    getBestMagicTarget(magicCard, isBot = false) {
        const allMonsters = [
            ...this.currentPlayer.monsterZone,
            ...this.getOpponent().monsterZone
        ];

        let bestTarget = null;
        let bestValue = -Infinity;

        allMonsters.forEach(monster => {
            if (monster.position !== 'attack') return;

            let value = this.evaluateMagicValue(magicCard, monster);
            if (isBot) {
                // 机器人的评估逻辑
                const isAlly = this.currentPlayer.monsterZone.includes(monster);
                value = isAlly ? value * 1.5 : -value;
            }

            if (value > bestValue) {
                bestValue = value;
                bestTarget = monster;
            }
        });

        return { target: bestTarget, value: bestValue };
    }

    // 获取当前玩家的对手
    getOpponent() {
        return this.currentPlayer === this.player ? this.robot : this.player;
    }

    // 检查是否有可用的战斗目标
    hasValidBattleTargets() {
        return this.getOpponent().monsterZone.length > 0;
    }

    // 获取可以被攻击的怪兽
    getAttackableMonsters() {
        return this.getOpponent().monsterZone;
    }

    // 检查是否可以使用魔法卡
    canUseMagic() {
        return this.currentState === GameState.BATTLE &&
               this.currentPlayer.magicZone.length > 0 &&
               this.hasValidMagicTargets();
    }

    // 检查是否可以放置卡牌
    canPlaceCards() {
        return this.currentState === GameState.PLACING &&
               (this.getAvailableMonsterZoneSlots(this.currentPlayer) > 0 ||
                this.getAvailableMagicZoneSlots(this.currentPlayer) > 0);
    }

    // 检查是否可以结束当前阶段
    canEndPhase() {
        return this.currentState !== GameState.SELECTING_ATTRIBUTE;
    }

    // 检查是否可以结束回合
    canEndTurn() {
        return this.currentState === GameState.BATTLE;
    }

    // 检查怪兽是否被摧毁
    checkMonsterDestruction() {
        const checkZone = (player) => {
            for (let i = player.monsterZone.length - 1; i >= 0; i--) {
                const monster = player.monsterZone[i];
                if (monster.stats.health <= 0) {
                    const destroyedMonster = player.monsterZone.splice(i, 1)[0];
                    player.graveyard.push(destroyedMonster);
                    return destroyedMonster;
                }
            }
            return null;
        };

        const destroyedMonsters = {
            player: checkZone(this.player),
            robot: checkZone(this.robot)
        };

        return destroyedMonsters;
    }

    // 获取游戏状态摘要
    getGameState() {
        return {
            currentPhase: this.currentState,
            currentPlayer: this.currentPlayer === this.player ? 'player' : 'robot',
            playerState: {
                lifePoints: this.player.lifePoints,
                deckCount: this.player.deck.length,
                handCount: this.player.hand.length,
                monsterCount: this.player.monsterZone.length,
                magicCount: this.player.magicZone.length,
                graveyardCount: this.player.graveyard.length
            },
            robotState: {
                lifePoints: this.robot.lifePoints,
                deckCount: this.robot.deck.length,
                handCount: this.robot.hand.length,
                monsterCount: this.robot.monsterZone.length,
                magicCount: this.robot.magicZone.length,
                graveyardCount: this.robot.graveyard.length
            }
        };
    }

    // 获取卡牌详细信息
    getCardDetails(cardId) {
        const findCard = (zones) => {
            for (const zone of zones) {
                const card = zone.find(c => c.id === cardId);
                if (card) return card;
            }
            return null;
        };

        const playerZones = [
            this.player.hand,
            this.player.monsterZone,
            this.player.magicZone,
            this.player.graveyard
        ];

        const robotZones = [
            this.robot.hand,
            this.robot.monsterZone,
            this.robot.magicZone,
            this.robot.graveyard
        ];

        return findCard(playerZones) || findCard(robotZones);
    }

    // 获取摧毁信息
    getDestructionMessage(destroyedMonsters) {
        let message = '';
        if (destroyedMonsters.player) {
            message += `\n${destroyedMonsters.player.name} 被摧毁了！`;
        }
        if (destroyedMonsters.robot) {
            message += `\n${destroyedMonsters.robot.name} 被摧毁了！`;
        }
        return message;
    }

    // 属性相克系统
    getAttributeBonus(attacker, defender) {
        const relationships = {
            '金': { '木': 1.5, '火': 0.5 },
            '木': { '土': 1.5, '金': 0.5 },
            '水': { '火': 1.5, '土': 0.5 },
            '火': { '金': 1.5, '水': 0.5 },
            '土': { '水': 1.5, '木': 0.5 }
        };

        const bonus = relationships[attacker.attribute]?.[defender.attribute];
        return bonus || 1;
    }

    // 计算实际伤害（考虑属性相克）
    calculateActualDamage(attacker, defender, baseDamage) {
        const attributeBonus = this.getAttributeBonus(attacker, defender);
        return Math.floor(baseDamage * attributeBonus);
    }

    evaluateMagicValue(magic, monster) {
        let value = 0;
        const isAlly = this.robot.monsterZone.includes(monster);

        switch (magic.effect.type) {
            case 'attack':
                value = this.evaluateAttackBuff(monster, magic.effect.value);
                break;
            case 'defense':
                value = this.evaluateDefenseBuff(monster, magic.effect.value);
                break;
            case 'health':
                value = this.evaluateHealthBuff(monster, magic.effect.value);
                break;
        }

        return isAlly ? value * 1.5 : -value;
    }

    evaluateAttackBuff(monster, value) {
        let baseValue = value;
        if (monster.stats.attack >= 5) baseValue *= 1.5;
        if (monster.stats.health >= 3) baseValue *= 1.3;
        return baseValue;
    }

    evaluateDefenseBuff(monster, value) {
        let baseValue = value;
        if (monster.stats.defense >= 5) baseValue *= 1.5;
        if (monster.stats.health <= 2) baseValue *= 1.3;
        return baseValue;
    }

    evaluateHealthBuff(monster, value) {
        let baseValue = value;
        if (monster.stats.health <= 2) baseValue *= 2;
        if (monster.stats.attack >= 5 || monster.stats.defense >= 5) baseValue *= 1.5;
        return baseValue;
    }
}

// 导出
export { GameModel, GameState, Attributes };
